/*
 * Word Probability Table 
 *
 * ZhihuiJin <zhihuijin@gmail.com>
 * vim: ts=4 sw=4 sts=4 et tw=78:
 * Sat Sep 15 16:22:13 JST 2007
 */ 

package jp.ac.utokyo.pinyomi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;


/**
 * Word probability table
 */
public class WordProbTable {
	private static WordProbTable instance;

    /** Word log-probability table */
    private HashMap<String,Double> wordMap;

    /** The minimal logProb in the table */
    private double minLogProb;

    /** Constructor
     *
     * @param fileName  file name of probability table
     */
    private WordProbTable(String fileName)  throws IOException {
    	System.out.println("Reading word file ...");
        wordMap = new HashMap<String,Double>();
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
		String strLine;

        minLogProb = 10000;
		while((strLine = in.readLine()) != null){
            if (strLine.trim().equals(""))
                continue;
            if (strLine.startsWith("#"))
                continue;

            String[] fields = strLine.split("\\s+");

            Double logProb = new Double(fields[1]);
            if (logProb.doubleValue() < minLogProb)
                minLogProb = logProb.doubleValue();

            wordMap.put(fields[0], logProb); 
        }
		
		minLogProb -=1;
    }
    
	public static synchronized WordProbTable getInstance(String fileName) throws IOException {
		if (instance == null) {
			instance = new WordProbTable(fileName);
		}
		return instance;
	}

    /** Return the probability of a word
     *
     * @param word word string
     * @return probability of the word
     */
    public double getProb(String word) {

        return Math.exp(getLogProb(word));
    }

    /** Return the log-probability of a word, if the word doesn't exist,
     * return the minimal vaule in the table
     *
     * @param word word string
     * @return log-probability of the word
     */
    public double getLogProb(String word) {
        Double logProb = wordMap.get(word);
        if (logProb == null)
            return minLogProb;
        else 
            return logProb.doubleValue();
    }

};

